//
//  MemoEntity.swift
//  memo
//
//  Created by DaleGuo on 2023/10/4.
//

import Foundation

extension MemoEntity: Comparable {
    public var id: String {
        // 只在第一次生成 没有setter方法。见awakeFromInsert
//        #if DEBUG
//        id_?
//        #else
        id_ ?? UUID().uuidString
//        #endif
    }
    
    var content: String {
        // getter setter
        get { content_ ?? "" }
        set { content_ = newValue }
    }
    
    var title: String {
        // getter setter
        get { title_ ?? "" }
        set { title_ = newValue }
    }
    
    var updated_date: Date {
        get { updated_date_ ?? Date() }
        set { updated_date_ = newValue }
    }
    
    public var todos: [TodoEntity] {
        let todosSet = todos_ as? Set<TodoEntity> ?? []
            
        return todosSet.sorted {
            $0.updated_date < $1.updated_date
        }
    }
    
    
    // 主要用于伪造数据
    convenience init(title: String,
                     content: String, updated_time: Date)
    {
        // 调用init
        self.init()  // 配置了context后
        self.title = title
        self.updated_date = updated_time
        self.content = content
    }
    
    // 每次创建项目都会调用的，（生命周期）复写
    override public func awakeFromInsert() {
        self.id_ = UUID().uuidString
    }
    
    public static func < (lhs: MemoEntity, rhs: MemoEntity) -> Bool {
        lhs.content < rhs.content
    }
    
    
    public static var example: MemoEntity {
        let context = PersistenceController.shared.viewContext
        let memoEntity = MemoEntity(context: context)
        memoEntity.title = "测试数据Title"
        memoEntity.content = "测试内容content测试内容content测试内容content测试内容content测试内容content测试内容content"
        memoEntity.updated_date = Date()
        
        let todo = TodoEntity(context: context)
        todo.content = "这是一个测试todo"
        todo.is_completed = false
        memoEntity.addToTodos_(todo)
        
        let todo_completed = TodoEntity(context: context)
        todo_completed.content = "这是第二个"
        todo_completed.is_completed = true
        memoEntity.addToTodos_(todo_completed)
        todo_completed.level = true
        
        return memoEntity
    }
}
